package com.cloud.upms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.tree.Tree;
import com.cloud.api.upms.enums.MenuExceptionEnum;
import com.cloud.api.upms.model.SysMenu;
import com.cloud.common.core.exception.ProjectException;
import com.cloud.common.core.result.Result;
import com.cloud.common.log.annotation.SysLog;
import com.cloud.common.log.enums.OperateTypeEnum;
import com.cloud.api.upms.domain.menu.MenuAddUpdateReq;
import com.cloud.upms.service.SysMenuService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import java.util.List;

/**
 * Author:  xuanning
 * Date:    2023/2/9 15:12
 */
@RestController
@AllArgsConstructor
public class SysMenuController {

    private final SysMenuService sysMenuService;

    /**
     * 新增
     * @return
     */
    @PostMapping(value = "/menu/add")
    @SaCheckPermission(value = "menu:add", orRole = "admin")
    @SysLog(title = "菜单管理",operate = OperateTypeEnum.ADD)
    public Result<?> add(@Valid @RequestBody MenuAddUpdateReq paramReq) {
        sysMenuService.addOrUpdate(paramReq);
        return Result.success();
    }

    /**
     * 更新
     * @return
     */
    @PostMapping(value = "/menu/update")
    @SaCheckPermission(value = "menu:update", orRole = "admin")
    @SysLog(title = "菜单管理",operate = OperateTypeEnum.UPDATE)
    public Result<?> update(@Valid @RequestBody MenuAddUpdateReq paramReq) {
        Long id=paramReq.getId();
        SysMenu menu=sysMenuService.getById(id);
        if(menu==null){
            throw new ProjectException(MenuExceptionEnum.MENU_NOT_EXIST);
        }
        sysMenuService.addOrUpdate(paramReq);
        return Result.success();
    }

    /**
     * 删除
     * @return
     */
    @GetMapping(value = "/menu/delete")
    @SaCheckPermission(value = "menu:delete", orRole = "admin")
    @SysLog(title = "菜单管理",operate = OperateTypeEnum.DELETE)
    public Result<?> delete(Long id) {
        sysMenuService.delete(id);
        return Result.success();
    }

    /**
     * 列表
     * @return
     */
    @GetMapping(value = "/menu/list")
    @SaCheckPermission(value = "menu", orRole = "admin")
    @SysLog(title = "菜单管理",operate = OperateTypeEnum.QUERY)
    public Result<?> listMenu() {
        List<Tree<Long>> tree= sysMenuService.listMenu();
        return Result.success(tree);
    }


    /**
     * 用户的菜单
     * @return
     */
    @GetMapping(value = "/menu/user-list")
    public Result<?> listUserMenu() {
        List<Tree<Long>> tree= sysMenuService.listUserMenu();
        return Result.success(tree);
    }


}
